package com.lottery.material.service.admin.article.impl;

import com.lottery.material.dao.article.ArticleInfoMapper;
import com.lottery.material.dao.article.ArticleTextInfoMapper;
import com.lottery.material.dao.circle.CircleInfoMapper;
import com.lottery.material.dao.system.UserMapper;
import com.lottery.material.enumeration.article.ArticleInfoEnum;
import com.lottery.material.enumeration.article.ArticleTextInfoEnum;
import com.lottery.material.enumeration.common.CommonEnum;
import com.lottery.material.pojo.article.ArticleInfo;
import com.lottery.material.pojo.article.ArticleTextInfo;
import com.lottery.material.pojo.circle.CircleInfo;
import com.lottery.material.pojo.page.Page;
import com.lottery.material.pojo.system.User;
import com.lottery.material.pojocustom.article.ArticleInfoCustom;
import com.lottery.material.service.admin.article.ArticleInfoService;
import com.lottery.material.util.AssertUtil;
import com.lottery.material.util.CalendarUtil;
import com.lottery.material.util.EnumUtil;
import com.lottery.material.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Description：文章信息服务接口实现类
 * Created by 朱正磊 on 2019-04-13 15:10
 */
@Slf4j
@Service("adminArticleInfoService")
public class ArticleInfoServiceImpl implements ArticleInfoService {

    private final ArticleInfoMapper articleInfoMapper;

    private final CircleInfoMapper circleInfoMapper;

    private final UserMapper userMapper;

    private final ArticleTextInfoMapper articleTextInfoMapper;

    @Autowired
    public ArticleInfoServiceImpl(ArticleInfoMapper articleInfoMapper,
                                  CircleInfoMapper circleInfoMapper,
                                  UserMapper userMapper,
                                  ArticleTextInfoMapper articleTextInfoMapper) {
        this.articleInfoMapper = articleInfoMapper;
        this.circleInfoMapper = circleInfoMapper;
        this.userMapper = userMapper;
        this.articleTextInfoMapper = articleTextInfoMapper;
    }

    /**
     * description：新增一条数据
     * user 朱正磊
     * time 2019-04-20 15:14
     * @param articleInfo 对象
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer add(ArticleInfo articleInfo) {
        articleInfo.setCreateTime(new Date());//设置创建时间
        articleInfo.setIsDelete((Integer) CommonEnum.IS_DELETE_FALSE.getValue());//设置未逻辑删除
        return articleInfoMapper.insertSelective(articleInfo);
    }

    /**
     * description：根据主键物理删除
     * user 朱正磊
     * time 2019-04-20 15:13
     * @param id 主键
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer deleteById(Integer id) {
        return articleInfoMapper.deleteByPrimaryKey(id);
    }

    /**
     * description：根据主键查询唯一数据
     * user 朱正磊
     * time 2019-04-20 15:15
     * @param id 主键
     * @return 返回唯一数据
     */
    @Override
    public ArticleInfo findById(Integer id) {
        return articleInfoMapper.selectByPrimaryKey(id);
    }

    /**
     * description：根据实体对象修改一条数据
     * user 朱正磊
     * time 2019-04-20 15:16
     * @param articleInfo 实体对象
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer updateById(ArticleInfo articleInfo) {
        articleInfo.setUpdateTime(new Date());
        return articleInfoMapper.updateByPrimaryKeySelective(articleInfo);
    }

    /**
     * description：根据请求对象修改一条数据（文章审核）
     * user 朱正磊
     * time 2019-04-20 15:16
     * @param request 请求对象
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer updateByAudit(HttpServletRequest request) {
        String articleState = request.getParameter("articleState");
        String auditReason = request.getParameter("auditReason");
        String id = request.getParameter("id");
        ArticleInfo articleInfo = new ArticleInfo();
        articleInfo.setId(Integer.valueOf(id));//主键
        articleInfo.setArticleState(Integer.valueOf(articleState));//审核状态
        articleInfo.setAuditReason(auditReason);//审核理由
        articleInfo.setAuditTime(new Date());//审核时间
        articleInfo.setAuditor(UserUtil.getUserId());//审核人ID
        return articleInfoMapper.updateByPrimaryKeySelective(articleInfo);
    }

    /**
     * description：查询扩展类分页列表
     * user 朱正磊
     * time 2019-04-17 17:01
     * @param page 分页对象
     * @return 返回扩展类分页列表数据
     */
    @Override
    public List<ArticleInfoCustom> findCustomListPage(Page page) {
        List<ArticleInfoCustom> list = articleInfoMapper.findCustomListPage(page);
        list.forEach(this::setCustom);
        return list;
    }

    /**
     * description：根据主键查询唯一扩展类数据
     * user 朱正磊
     * time 2019-04-17 17:03
     * @param id 主键
     * @return 返回唯一扩展类数据
     */
    @Override
    public ArticleInfoCustom findCustomById(Integer id) {
        ArticleInfoCustom custom = articleInfoMapper.findCustomById(id);
        this.setCustom(custom);
        return custom;
    }

    /**
     * description：设置扩展类的扩展属性
     * user 朱正磊
     * time 2019-04-17 17:48
     * @param custom 扩展类对象
     */
    private void setCustom(ArticleInfoCustom custom) {
        //创建时间
        custom.setCreateTimeFormat(CalendarUtil.dateToString(custom.getCreateTime()));
        //是否删除（1：否；2：是）
        custom.setIsDeleteDesc(EnumUtil.getDescriptionByCodeValue(CommonEnum.IS_DELETE, custom.getIsDelete(), CommonEnum.class));
        //审核时间
        custom.setAuditTimeFormat(CalendarUtil.dateToString(custom.getAuditTime()));
        //公开时间
        custom.setPublicTimeFormat(CalendarUtil.dateToString(custom.getPublicTime()));
        //推广时间
        custom.setPromotionTimeFormat(CalendarUtil.dateToString(custom.getPromotionTime()));
        //置顶时间
        custom.setTopTimeFormat(CalendarUtil.dateToString(custom.getTopTime()));
        //更新时间
        custom.setUpdateTimeFormat(CalendarUtil.dateToString(custom.getUpdateTime()));
        //文章状态（1：待审核；2：审核不通过/驳回；3：审核通过；）
        custom.setArticleStateDesc(EnumUtil
                .getDescriptionByCodeValue(ArticleInfoEnum.ARTICLE_STATE, custom.getArticleState(), ArticleInfoEnum.class));
        //是否收费（1：否；2：是）
        custom.setIsChargeDesc(EnumUtil
                .getDescriptionByCodeValue(ArticleInfoEnum.IS_CHARGE, custom.getIsCharge(), ArticleInfoEnum.class));
        //赛事是否结束（1：否；2：是）
        custom.setIsCompetitionEndDesc(EnumUtil
                .getDescriptionByCodeValue(ArticleInfoEnum.IS_COMPETITION_END, custom.getIsCompetitionEnd(), ArticleInfoEnum.class));
        //收费文章是否公开（1：否；2：是；）
        custom.setIsEndPublicDesc(EnumUtil
                .getDescriptionByCodeValue(ArticleInfoEnum.IS_END_PUBLIC, custom.getIsEndPublic(), ArticleInfoEnum.class));
        //是否存在赛事（1：否；2：是）
        custom.setIsExistCompetitionDesc(EnumUtil
                .getDescriptionByCodeValue(ArticleInfoEnum.IS_EXIST_COMPETITION, custom.getIsExistCompetition(), ArticleInfoEnum.class));
        //是否进热贴（1：否；2：是）
        custom.setIsHotDesc(EnumUtil
                .getDescriptionByCodeValue(ArticleInfoEnum.IS_HOT, custom.getIsHot(), ArticleInfoEnum.class));
        //是否推广（1：否；2：是）
        custom.setIsPromotionDesc(EnumUtil
                .getDescriptionByCodeValue(ArticleInfoEnum.IS_PROMOTION, custom.getIsPromotion(), ArticleInfoEnum.class));
        //是否置顶（1：否；2：是）
        custom.setIsTopDesc(EnumUtil
                .getDescriptionByCodeValue(ArticleInfoEnum.IS_TOP, custom.getIsTop(), ArticleInfoEnum.class));
        //锁状态（1：锁着；2：开锁）
        custom.setLockStateDesc(EnumUtil
                .getDescriptionByCodeValue(ArticleInfoEnum.LOCK_STATE, custom.getLockState(), ArticleInfoEnum.class));
        //所属圈子名称
        CircleInfo circleInfo = circleInfoMapper.selectByPrimaryKey(custom.getCircleId());
        custom.setCircleName(circleInfo.getCircleName());
        //审核人
        User user = userMapper.selectById(custom.getAuditor());
        if (AssertUtil.isNotEmpty(user)) {
            custom.setAuditorName(user.getUSERNAME());
        }
        //设置文章收费部分内容和免费部分内容
        this.setContent(custom);
    }

    /**
     * description：设置文章收费部分内容和免费部分内容
     * user 朱正磊
     * time 2019-06-04 13:16
     * @param custom 扩展类对象
     */
    private void setContent(ArticleInfoCustom custom) {
        //免费部分内容
        StringBuilder freeContent = new StringBuilder();
        //收费部分内容
        StringBuilder chargeContent = new StringBuilder();
        //获取文章id
        String articleId = custom.getArticleId();
        //根据文章id查询相关的文章免费内容信息
        List<ArticleTextInfo> articleTextInfoFreeList = articleTextInfoMapper
                .selectByArticleId(articleId, (Integer) ArticleTextInfoEnum.TEXT_CHARGE_TYPE_FREE.getValue());
        for (ArticleTextInfo articleTextInfo : articleTextInfoFreeList) {
            freeContent.append(articleTextInfo.getContent());
        }
        //根据文章id查询相关的文章收费内容信息
        List<ArticleTextInfo> articleTextInfoChargeList = articleTextInfoMapper
                .selectByArticleId(articleId, (Integer) ArticleTextInfoEnum.TEXT_CHARGE_TYPE_CHARGE.getValue());
        for (ArticleTextInfo articleTextInfo : articleTextInfoChargeList) {
            chargeContent.append(articleTextInfo.getContent());
        }
        custom.setFreeContent(freeContent.toString());
        custom.setChargeContent(chargeContent.toString());
    }

    /**
     * description：根据主键删除一条数据（逻辑删除）
     * user 朱正磊
     * time 2019-04-30 11:30
     * @param id 主键
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer deleteLogicById(Integer id) {
        ArticleInfo articleInfo = new ArticleInfo();
        articleInfo.setId(id);
        articleInfo.setIsDelete((Integer) CommonEnum.IS_DELETE_TRUE.getValue());
        Integer flag = articleInfoMapper.updateByPrimaryKeySelective(articleInfo);
        log.info("【逻辑删除持久化操作数据库状态：flag = {}】", flag);
        return flag;
    }
    
}
